package ynu.edu.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ynu.edu.common.service.LogicService;
import ynu.edu.dao.IBusinessDao;
import ynu.edu.dao.ICustomerDao;
import ynu.edu.dao.IUserDao;
import ynu.edu.entity.Business;
import ynu.edu.entity.Customer;
import ynu.edu.entity.User;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class UserService extends LogicService<IUserDao, User,Long> {
    public UserService(@Autowired IUserDao dao) {
        super(dao);
    }

    @Resource
    private ICustomerDao customerDao;
    @Resource
    private IBusinessDao businessDao;

    /**
     *  TODO
     * @param userPhone
     * @param password
     * @return
     */
    public User login(String userPhone, String password){
        if (StringUtils.isNoneBlank(userPhone)&&StringUtils.isNoneBlank(password)){
            return getDAO().findUserByUserPhoneAndPassword(userPhone,password);
        }
        return null;
    }

    public User register(User user){
        //判断用户是否已存在
        User userDB = getDAO().findUserByUserPhone(user.getUserPhone());
        if (Objects.isNull(userDB)){
            if (Objects.equals(user.getType(), User.TYPE_CUSTOMER)){
                Customer customer = new Customer();
                BeanUtils.copyProperties(user,customer);
                return customerDao.save(customer);
            } else if (Objects.equals(user.getType(), User.TYPE_BUSINESS)) {
                Business business = new Business();
                BeanUtils.copyProperties(user,business);
                return businessDao.save(business);
            }
            return null;
        }
        return null;
    }
}
